package com.sky.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.sky.constant.MessageConstant;
import com.sky.dto.UserLoginDTO;
import com.sky.entity.User;
import com.sky.exception.DeletionNotAllowedException;
import com.sky.mapper.UserMapper;
import com.sky.properties.WeChatProperties;
import com.sky.service.UserService;
import com.sky.utils.HttpClientUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.Map;

@Service
public class UserServiceImpl implements UserService {

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private WeChatProperties weChatProperties;

    @Override
    public User wxLogin(UserLoginDTO userLoginDTO) {
        // 通过 HttpClient 构造请求 ，发送请求到微信平台
        // 请求地址： https://api.weixin.qq.com/sns/jscode2session
        // 请求参数： appid=wxac8297628480324c&secret=49bb351684db61809ca36a8530b247f6&js_code=0e1qW41w3XpRv13eas0w3YJITO2qW41C&grant_type=authorization_code

        String url = "https://api.weixin.qq.com/sns/jscode2session";

        Map<String, String> paramMap = new HashMap<>();
        paramMap.put("appid", weChatProperties.getAppid());
        paramMap.put("secret", weChatProperties.getSecret());
        paramMap.put("js_code", userLoginDTO.getCode());
        paramMap.put("grant_type", "authorization_code");
        String jsonResult = HttpClientUtil.doGet(url, paramMap);

        // 解析详情数据 获取 openId 判断该值是否存在
        JSONObject jsonObject = JSON.parseObject(jsonResult);
        String openid = (String) jsonObject.get("openid");

        // 如果获取 openId 获取失败，抛出自定义异常 -- 登录失败
        if (openid == null) {
            throw new DeletionNotAllowedException(MessageConstant.USER_NOT_LOGIN);
        }

        // 如果有值，查询数据库 user 表，
        User user = userMapper.selectByOpenId(openid);

        // 判断该用户是否为新用户 如果返回值为空 代表是新用户
        if (user == null) {
            // 需要完成自动注册 往 user 表中新增一条数据
            user = new User();
            user.setOpenid(openid);
            user.setName("u_" + openid.substring(5, 10));
            user.setCreateTime(LocalDateTime.now());
            userMapper.insert(user);
        }

        // 如果返回值不为空 代表该用户之前登录过 直接返回用户信息
        return user;
    }
}
